<template>
  <div>
    <el-card class="w_100" v-loading="spinning">
      <template #header>
        <header>
          <div class="left">每日合格证开具实时数据</div>
          <div class="right">
            <el-button @click='handleExportXlsMy' type="primary" size="small">下载</el-button>
            <el-select v-model="queryParam.selectUnitId" size="mini" style="width: 150px;margin-left:10px;"
                       @change='unitIdClick' placeholder="请选择区域"
                       v-hasPermi="['nongjt:user:list']" >
              <el-option v-for="{id,area} of unitList" :key="id" :label="area" :value="id">
              </el-option>
            </el-select>
            <el-date-picker :clearable="false"
                            v-model="queryParam.selectYearMonth" value-format="yyyy-MM" style="width: 120px;margin-left: 10px;"
                            type="month" size="mini" placeholder="请选择月份">
            </el-date-picker>
          </div>
        </header>
      </template>
      <div id='DailyRealTimeCharts' v-show='isShowChart' style='width: 100%;height: 300px;'></div>
      <div v-if='!isShowChart' style='line-height: 300px;font-size: 24px;text-align: center'>
        该条件下无统计数据
      </div>
    </el-card>
  </div>
</template>

<script>
import {echartResizeMixins} from "@/views/nongjt/charts/echartResizeMixins";
import {mapGetters} from "vuex";
import {getAction, getActionSimple} from "@/utils/axiosUtils";
import dayjs from "dayjs";

let echarts = require('echarts')

export default {
  name: 'DailyRealTimeCharts',
  mixins:[echartResizeMixins],
  data() {
    return {
      url: {
        DailyRealTime: '/nongjt/certificateCount/DailyRealTime',
        exportXlsUrl: '/nongjt/certificateCount/exportXlsDailyRealTime'
      },
      spinning: false,
      isShowChart: true,
      queryParam: {
        //默认年月
        selectYearMonth: dayjs().format("YYYY-MM"),
        //选中的单位id
        selectUnitId: null
      },
      chart: null,
      option: {
        title: {
          text: '合格证开具数量',
          left: 'center'
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            interval: 1,
            // rotate: 45
          }
        },
        yAxis: {
          type: 'value'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}日 开具数量:{c}'
        },
        //保存为图片，等其他功能,在右上角
        toolbox: {
          feature: {
            saveAsImage: { show: true },
            // dataView:{show: true},//数据视图

          }
        },
        // toolbox: {
        //   show: true,
        //   feature: {
        //     dataZoom: {
        //       yAxisIndex: 'none'
        //     },
        //     dataView: { readOnly: false },
        //     magicType: { type: ['line', 'bar'] },
        //     restore: {},
        //     saveAsImage: {}
        //   }
        // },
        series: [{
          data: [],
          type: 'bar',
          showBackground: true,
          label: {
            show: true,
            formatter: '{c}',
            position: 'top',
            color: () => {
            }
          },
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          }
        }]
      },
      //图标标题
      title: '每日合格证开具实时数据'
    }
  },
  mounted() {
    this.queryParam.selectUnitId = this.selectUnitId
    //只有值的时候才发起请求
    if (this.queryParam.selectUnitId){
      this.unitIdClick(this.queryParam.selectUnitId)
    }
  },
  methods: {
    //初始化图表
    initChart() {
      if (!this.chart) {
        const dom = document.querySelector('#DailyRealTimeCharts')
        this.chart = echarts.init(dom)
        this.chart.on('click',(params)=>{
          const {name} = params
          let selectTimeMoment = this. queryParam.selectYearMonth
          let seriesName = this.unitList.find(t=>+t.id === +this.queryParam.selectUnitId)
          let dateBegin = dayjs(selectTimeMoment).format('YYYY-MM') + '-'+ name
          let dateEnd = dateBegin
          this.$router.push({ path: 'nongjt/certificate?area=' + seriesName + '&dateBegin=' + dateBegin + '&dateEnd=' + dateEnd});
        })
      }
      this.chart.setOption(this.option)
    },
    //区域选择事件
    unitIdClick(n) {
      if (n) {
        let yearMonthStr = this.queryParam.selectYearMonth
        let param = {
          yearMonthStr: yearMonthStr,
          unitId: n
        }
        this.getPrintCountStatistics(param)
      }

    },
    //获取合格证开具数量
    async getPrintCountStatistics(param) {
      try {
        let {yearMonthStr} = param
        this.spinning = true
        const result = await getActionSimple(this.url.DailyRealTime, param)
        const [year,month] = yearMonthStr.split("-")
        let xAxis = this.setXAxis(year,month)
        const resultDate = this.dateMapping(xAxis, result)

        this.option.xAxis.data = resultDate.map(t => t.xAxis)
        this.option.series[0].data = resultDate.map(t => t.yAxis)
        const total = this.option.series[0].data.reduce((pre, curr) => pre + curr)

        this.option.title.text = param.yearMonthStr.substring(0,7) + '月' + this.title + '(' + total + ')'
        this.initChart()
      } catch (e) {
        console.log(e)
      }finally{
        this.spinning = false
      }
    },
    //构建x轴
    setXAxis(year,month) {
      let xAxiosArray = []
      let d = new Date(year, month, 0);

      for (let i = 1; i <= d.getDate(); i++) {
        xAxiosArray.push(i < 10 ? '0' + i : i + '')
      }
      return xAxiosArray
    },
    /**
     * x轴与数据进行映射,组装成需要展示的数据
     * @param xAxis x轴数据
     * @param dataList 接口返回的数据
     * @returns {*[]} 返回结果为数组 数组子元素为对象,属性有xAxis 与yAxis 分别对应x轴与y轴的数据
     */
    dateMapping(xAxis, dataList) {
      let result = []
      for (let x of xAxis) {
        let obj = { xAxis: x }
        const findObj = dataList.find(t => t.title === x)
        if (findObj) {
          obj.yAxis = findObj.count
        } else {
          obj.yAxis = null
        }
        result.push(obj)
      }
      return result
    },
    async handleExportXlsMy() {
      this.spinning = true
      try {
        let param = {
          unitId:this.queryParam.selectUnitId,
          yearMonthStr:this.queryParam.selectYearMonth,
        }
        console.log("导出参数", param)
        this.download(this.url.exportXlsUrl, {
          ...param
        }, `每日合格证开具实时数据.xlsx`)
      } finally {
        this.spinning = false
      }
    }
  },
  computed:{
    ...mapGetters([
      'unitList',
      'selectUnitId',
    ]),
  },
  watch:{
    selectUnitId(n){
      if (n){
        this.queryParam.selectUnitId = n
        this.unitIdClick(n)
      }
    },
    //监听年月的选择
    'queryParam.selectYearMonth'(n) {
      if (n) {
        let param = {
          yearMonthStr: n,
          unitId: this.queryParam.selectUnitId,
        }
        this.getPrintCountStatistics(param)
      } else {
        const param = {
          unitId: this.queryParam.selectUnitId,
          yearMonthStr:dayjs().format("'YYYY-MM")
        }
        this.getPrintCountStatistics(param)
      }
    },
  }
}
</script>
<style lang="less" scoped>
.w_100{
  width: 100%;
}
header{
  display: flex;
  justify-content: space-between;
  align-content: center;

  .left{
    font-weight: bold;
  }
}
</style>
